package io.dshubs.archives.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.dshubs.archives.dao.ArchiveBaseClassMapper;
import io.dshubs.archives.dao.ArchiveDestroyMapper;
import io.dshubs.archives.entity.ArchiveAppraisal;
import io.dshubs.archives.entity.ArchiveBaseCategory;
import io.dshubs.archives.entity.ArchiveDestroy;
import io.dshubs.archives.service.ArchiveDestroyService;
import io.dshubs.commons.mybatis.enums.DelFlagEnum;
import io.dshubs.commons.mybatis.service.impl.BaseServiceImpl;
import io.dshubs.commons.security.user.SecurityUser;
import io.dshubs.commons.security.user.UserDetail;
import io.dshubs.commons.tools.constant.Constant;
import io.dshubs.commons.tools.enums.SuperAdminEnum;
import io.dshubs.commons.tools.page.PageData;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 档案销毁表 服务实现类
 * </p>
 *
 * @author tan
 * @since 2021-08-27
 */
@Service
public class ArchiveDestroyServiceImpl extends BaseServiceImpl<ArchiveDestroyMapper, ArchiveDestroy> implements ArchiveDestroyService {
    @Autowired
    private ArchiveBaseClassMapper archiveBaseClassMapper;
    @Override
    public PageData<ArchiveDestroy> page(Map<String, Object> params) {
        IPage<ArchiveDestroy> page = baseDao.selectPage(
                getPage(params, Constant.CREATE_DATE, false),
                getWrapper(params)
        );
        PageData<ArchiveDestroy> pageData = getPageData(page, ArchiveDestroy.class);
        List<ArchiveDestroy> list = pageData.getList();
        if(list.size() > 0) {
            list.forEach(item->{
                ArchiveBaseCategory archiveBaseCategory = archiveBaseClassMapper.selectById(item.getCategoryId());
                item.setCategoryName(archiveBaseCategory == null ? null : archiveBaseCategory.getName());
            });
        }
        return pageData;
    }


    private QueryWrapper<ArchiveDestroy> getWrapper(Map<String, Object> params){
        String destroyTitle = (String)params.get("destroyTitle");
        String fileNumber = (String)params.get("fileNumber");
        QueryWrapper<ArchiveDestroy> wrapper = new QueryWrapper<>();
        wrapper.eq(Constant.DEL_FLAG, DelFlagEnum.NORMAL.value());
        wrapper.like(StringUtils.isNotBlank(destroyTitle), "destroy_title", destroyTitle);
        wrapper.eq(StringUtils.isNotBlank(fileNumber),"file_number",fileNumber);
        UserDetail user = SecurityUser.getUser();
        if(user.getSuperAdmin() != SuperAdminEnum.YES.value()) {
            wrapper.eq("tenant_code",user.getTenantCode());
        }
        return wrapper;
    }
}
